import paramiko
import os
import logging

"""
功能：上传生成的配置文件
"""

# 目标节点
nodes = ["mng1", "mng2", "node1", "node2", "node3", "node4"]

# 账号密码
username = "***"
password = "***"

# 配置文件路径映射
path_mappings = [
    # {"local": "output/test/", "ssh": "/data/"},
    {"local": "output/hadoop/", "ssh": "/data/hadoop/etc/hadoop/"},
    {"local": "output/hbase/", "ssh": "/data/hbase/conf/"}
]


def upload_file():
    try:
        for node in nodes:
            transport = paramiko.Transport(node, 22)
            transport.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(transport)
            for path in path_mappings:
                local_path = path.get("local")
                remote_path = path.get("ssh")
                files = os.listdir(local_path)
                for file in files:
                    lf = os.path.join(local_path, file)
                    rf = os.path.join(remote_path, file)
                    print("{:30}\t{:10}\t{:30}".format(lf, node, rf))
                    sftp.put(lf, rf)
            transport.close()
        return True
    except Exception as e:
        logging.error(str(e))
        return False


if __name__ == '__main__':
    # files = os.listdir('output/hadoop/')
    # for file in files:
    #     print(file)
    ret = upload_file()
    print("upload result:", ret)


